package com.immortal.module.oauth;

import com.immortal.core.configure.ImConfig;
import com.immortal.module.oauth.authorize.OpenAuthorizeConfigManager;
import com.immortal.module.oauth.exception.CustomOauthAccessDeniedHandler;
import com.immortal.module.oauth.exception.CustomOauthAuthExceptionEntryPoint;
import com.immortal.module.oauth.exception.CustomWebResponseExceptionTranslator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;


/**
 * @author xukk
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    @Autowired
    private ImConfig config;
    @Autowired
    private CustomWebResponseExceptionTranslator customWebResponseExceptionTranslator;
    @Bean
    OpenAuthorizeConfigManager openAuthorizeConfigManager() {
        return new OpenAuthorizeConfigManager();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .requestMatchers().antMatchers(config.getOauthUrl().getAuth().toArray(new String[0]))
                .and().authorizeRequests();
        http.exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
        openAuthorizeConfigManager().config(registry);
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        super.configure(resources);
        resources.authenticationEntryPoint(new CustomOauthAuthExceptionEntryPoint(customWebResponseExceptionTranslator))
                .accessDeniedHandler(new CustomOauthAccessDeniedHandler(customWebResponseExceptionTranslator));
    }
}
